
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        :permission="permissionList"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click="myAdd"
            >添 加</el-button
          >
          <!-- <el-button
            type="primary"
            size="small"
            @click="handleBatchSubmit"
            v-if="permissionList.submitBtn"
            hidden="true"
            >提 交</el-button
          > -->
          <el-button
            type="primary"
            size="small"
            @click="handleBatchDelete"
            v-if="permissionList.delBtn"
            >删 除</el-button
          >
          <el-button type="primary" size="small" v-if="false" @click="handleExport"
            >导 出</el-button
          >
          <el-button type="primary" size="mini" @click="submitData">加入报表差错</el-button>
        </template>
        <template slot="menu" slot-scope="{ row }">
          <el-button
            type="text"
            size="small"
            @click="handleEdit(row)"
            icon="el-icon-edit"
            v-if="permissionList.editBtn && row.submitStatus == '0' && row.isMerge == '0'"
            >编 辑</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="mergeEdit(row)"
            icon="el-icon-edit"
            v-if="permissionList.editBtn && row.submitStatus == '0' && row.isMerge == '1'"
            >编 辑</el-button
          >
          <el-button
            icon="el-icon-check"
            type="text"
            size="small"
            @click="openPastRecords(row)"
            >查看历史记录</el-button
          >
        </template>
      </avue-crud>
      <open-dialog
        :DialogVisible.sync="addVisableDialog"
        title="添加"
        width="70%"
      >
        <el-form v-if="addVisableDialog">
          <avue-form ref="form" v-model="formAdd" :option="tableOptionAdd"></avue-form>
          <div class="bottom-menu">
            <el-button type="primary" @click="saveBefore">保存</el-button>
            <el-button type="primary" @click="addVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
      <open-dialog
        :DialogVisible.sync="editVisableDialog"
        title="编辑"
        width="70%"
      >
        <el-form v-if="editVisableDialog">
          <avue-form v-model="formEdit" :option="tableOptionAdd"></avue-form>
          <div class="bottom-menu">
            <el-button type="primary" @click="editBefore">保存</el-button>
            <el-button type="primary" @click="editVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
      <open-dialog
        :DialogVisible.sync="mergeDialogVisible"
        title="编辑"
        width="70%"
      >
        <el-form v-if="mergeDialogVisible">
          <avue-form v-model="formMergeEdit" :option="tableOptionMergeEdit"></avue-form>
          <div class="bottom-menu">
            <el-button type="primary" @click="mergeEditBefore">保存</el-button>
            <el-button type="primary" @click="mergeDialogVisible = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
      <open-dialog title="历史记录" :DialogVisible.sync="visableDialogRecords">
        <el-form label-width="60px">
          <avue-crud
            :data="tableDataRecords"
            :option="tableOptionRecords"
          >
          </avue-crud>
          <div class="bottom-menu-records">
            <el-button type="primary" @click="visableDialogRecords = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
    <addReportEditor ref="addReportEditor" @addReportSuccess="getList"></addReportEditor>
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  exportExcel,
  submit,
  batchDelete,
  getInputPassengerWorkOther,
  queryPastRecords,
  getHappenCause
} from "@/api/subwaystm/swstpassengerworkother";
import {
  tableOption,
  tableOptionAdd,
  tableOptionMergeEdit,
  tableOptionRecords
} from "@/const/crud/subwaystm/swstpassengerworkother";
import { handleExcelResponse } from "@/util/util";
import { mapGetters } from "vuex";
import { dateFormat } from "@/util/date";
import baseCrud from "@/mixins/base-crud";
import transitUtil from "@/api/subwayRat/transitUtil";
import addReportEditor from '@/views/stationTiecketManager/xianWngCJXXQR/BBCCGG/BBCCGGSQ/Editor';

export default {
  name: "swstpassengerworkother",
  mixins: [baseCrud("subwaystm/swstpassengerworkother")],
  components: {
    addReportEditor
  },
  data() {
    return {
      visableDialogRecords: false,
      tableDataRecords: [],
      tableOptionRecords: tableOptionRecords,
      searchForm:{
        submitStatus:'0'
      },
      formAdd: {},
      formEdit: {},
      addVisableDialog: false,
      editVisableDialog: false,
      tableOptionAdd: tableOptionAdd,
      tableOptionMergeEdit: tableOptionMergeEdit,
      mergeDialogVisible: false,
      signs: 0,
      selectKeys:[]
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.stm_sw_st_input_passenger_work_other_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.stm_sw_st_input_passenger_work_other_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.stm_sw_st_input_passenger_work_other_edit,
          false
        ),
        submitBtn: this.vaildData(
          this.permissions.stm_sw_st_input_passenger_work_other_submit,
          false
        ),
      };
    },
  },
  created() {
    this.otherVueAction();
  },
  methods: {
    async submitData() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      if (this.$refs.crud.tableSelect.length != 1) {
        this.$message.error("只能选择一条数据");
        return false;
      }
      let inputTimes = "";
      let res = false;
      let ress = false;
      for (const table of this.$refs.crud.tableSelect) {
        if (table.submitStatus != "1") {
          this.$message.error("请选择已提交的数据");
          return false;
        }else{
          let now = new Date(table.inputTime);
          inputTimes = dateFormat(now).substring(0, 10);
          if (table.isAddReprotError == "1") {
            res = await this.$confirm('该数据已加入报表差错，是否重新加入？', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            });
            if (!res) {
              return;
            }else{
              ress = true;
            }
          }
        }
      }
      if(res==false){
        ress = await this.$confirm("是否加入报表差错", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        });
      }
      if (!ress) {
        return;
      }
      this.selectKeys = this.$refs.crud.tableSelect;
      let param={
        dialogTitle: "加入报表差错",
        diffAmountId:this.selectKeys[0].id,
        dataSourceTable:"sw_st_input_passenger_work_other",
        lineCode:this.selectKeys[0].lineCode,
        stationCode:this.selectKeys[0].stationCode,
        //bomCode:this.selectKeys[0].bomCode,
        reprotTime:inputTimes,
        reportNameId:10,
        deviceNo:this.selectKeys[0].deviceOperateNum,
        settleBeginTime:inputTimes,
        settleEndTime:inputTimes,
        userCodes:this.selectKeys[0].conductorCode,
        showType:3,
        dataSource:1,
        page:this.page
      };
      this.$refs.addReportEditor.others_report_add_call(param);
    },
    async queryPastRecords(row){
      let param={};
      param.id=row.id;
      await queryPastRecords(param)
        .then(res => {
          this.tableDataRecords = res.data.data;
        })
    },
    openPastRecords(row){
      this.tableDataRecords = [];
      this.queryPastRecords(row);
      this.visableDialogRecords=true;
    },
    myAdd: function () {
      for (var i in this.formAdd) {
          this.formAdd[i] = "";
      }
      let now = new Date();
      if (now.getHours() < 6) {
        now.setDate((now.getDate() - 1));
        this.formAdd.inputTime = dateFormat(now).substr(0, 10) + " 02:00:00";
      }else{
        this.formAdd.inputTime = dateFormat(now);
      }
      // let inputTime = new Date();
      // if (inputTime.getHours() < 6) {
      //   inputTime.setDate(inputTime.getDate() - 1);
      // }
      // this.formAdd.inputTime = dateFormat(inputTime);
      this.addVisableDialog = true;
    },
    async getHappenCause(happenCause){
      await getHappenCause(happenCause)
        .then((response) => {
          let res = response.data.data;
          this.signs = res.signs;
        })
    },
    saveBefore(){
      if(this.formAdd.dataType == '2' || this.formAdd.dataType == '3' ){
        if(this.validatenull(this.formAdd.failureOperator)||this.validatenull(this.formAdd.sellOperator)){
          this.$message.info("请选择(故障/发售)运营商和(进/出站)售卖运营商！");
          return;
        }
      }
      if(!this.validatenull(this.formAdd.happenCause)){
        this.getHappenCause(this.formAdd.happenCause).then(response =>{
          if(this.signs == 1){
            if (this.formAdd.amount > 0) {
              this.$message.info("请检查当前产生原因的金额应该为负数！");
              return;
            }
          }
          this.save();
        })
      }else{
          this.save();
      }
    },
    save: function () {
      // if (this.formAdd.dataType == 1) {
      //   if (
      //     this.formAdd.happenCause == 1 ||
      //     this.formAdd.happenCause == 5 ||
      //     this.formAdd.happenCause == 6
      //   ) {
      //     if (this.formAdd.amount > 0) {
      //       this.$message.info("请检查当前产生原因的金额应该为负数！");
      //       return;
      //     }
      //   }else{
      //     if (this.formAdd.amount < 0) {
      //       this.$message.info("请检查当前产生原因的金额应该为正数！");
      //       return;
      //     }
      //   }
      // }else if(this.formAdd.dataType == 3){
      //     if (this.formAdd.amount > 0) {
      //       this.$message.info("请检查当前数据类型的金额应该为负数！");
      //       return;
      //     }
      // }
      let now = new Date();
      let future = new Date();
      if (now.getHours() < 6) {
        now.setDate(now.getDate() - 1);
      }else{
        future.setDate(now.getDate() + 1);
      }
      this.$refs.form.validate(vaild=>{
        if(vaild){
            if(
              this.formAdd.inputTime >= dateFormat(future).substr(0, 10) + " 02:00:00" || 
              this.formAdd.inputTime < dateFormat(now).substr(0, 10) + " 02:00:00"
            ){
              this.$confirm("事务日期不是系统默认时间,是否保存？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(() => {
                addObj(this.formAdd)
                  .then((data) => {
                    this.$message.success("添加成功");
                    this.getList(this.page);
                    this.addVisableDialog = false;
                    done();
                  })
                  .catch(() => {});
              })
            } else {
              addObj(this.formAdd)
                .then((data) => {
                  this.$message.success("添加成功");
                  this.getList(this.page);
                  this.addVisableDialog = false;
                  done();
                })
                .catch(() => {});
            }
          }
        })
    },
    // handleEdit(row) {
    //   this.$refs.crud.rowEdit(row);
    // },
    handleEdit:function(row) {
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formEdit=res;
        })
        .then(() => {
          this.editVisableDialog = true;
        });
    },
    mergeEdit(row) {
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formMergeEdit=res;
        })
        .then(() => {
          this.mergeDialogVisible = true;
        });
    },
    editBefore(){
      if(this.formEdit.dataType == '2' || this.formEdit.dataType == '3' ){
        if(this.validatenull(this.formEdit.failureOperator)||this.validatenull(this.formEdit.sellOperator)){
          this.$message.info("请选择(故障/发售)运营商和(进/出站)售卖运营商！");
          return;
        }
      }
      this.getHappenCause(this.formEdit.happenCause).then(response =>{
        if(this.signs == 1){
          if (this.formEdit.amount > 0) {
            this.$message.info("请检查当前产生原因的金额应该为负数！");
            return;
          }
        }
        this.edit();
      })
    },
    edit:function() {
      putObj(this.formEdit)
        .then((data) => {
          this.$message.success("编辑成功");
          this.getList(this.page);
          this.editVisableDialog = false;
          done();
        })
        .catch(() => {});
    },
    mergeEditBefore(){
      if(this.formEdit.dataType == '2' || this.formEdit.dataType == '3' ){
        if(this.validatenull(this.formEdit.failureOperator)||this.validatenull(this.formEdit.sellOperator)){
          this.$message.info("请选择(故障/发售)运营商和(进/出站)售卖运营商！");
          return;
        }
      }
      this.getHappenCause(this.formMergeEdit.happenCause).then(response =>{
        if(this.signs == 1){
          if (this.formMergeEdit.amount > 0) {
            this.$message.info("请检查当前产生原因的金额应该为负数！");
            return;
          }
        }
        this.mergeEditSubmit();
      })
    },
    mergeEditSubmit() {
      putObj(this.formMergeEdit)
        .then((data) => {
          this.$message.success("编辑成功");
          this.getList(this.page);
          this.mergeDialogVisible = false;
          done();
        })
        .catch(() => {});
    },
    handleBatchSubmit() {
      var tableSelect = this.$refs.crud.tableSelect;
      if (tableSelect.length == 0) {
        this.$message.info("请选择要提交的记录");
        return;
      }
      var ids = tableSelect.map((row) => row.id);
      submit(ids).then((response) => {
        this.$message.success("提交成功");
        this.getList(this.page);
      });
    },
    handleBatchDelete() {
      var tableSelect = this.$refs.crud.tableSelect;
      if (tableSelect.length == 0) {
        this.$message.info("请选择要删除的记录");
        return;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        if (table.submitStatus != "0") {
          this.$message.error("请选择未提交的数据");
          return false;
        }
        if (table.reportModifyStatus == "1") {
          this.$message.error("报表修改状态为“是”的情况下，不允许删除数据");
          return false;
        }
        ids.push(table.id);
      }
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        batchDelete(ids)
          .then((data) => {
            this.$message.success("删除成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      });
      // var ids = tableSelect.map(row => row.id)
      // batchDelete(ids).then(response => {
      //   this.$message.success('删除成功')
      //   this.getList(this.page)
      // })
    },
    handleExport() {
      let query = Object.assign(
        {
          current: this.page.currentPage,
          size: this.page.pageSize,
        },
        this.searchForm
      );
      exportExcel(query).then((response) => {
        handleExcelResponse(response);
      });
    },
    otherVueAction(){
      transitUtil.$on('updateReport_call_10',(param)=>{
        let p=param;
        getInputPassengerWorkOther(p).then(response => {
          this.tableData = response.data.data;
          this.tableLoading = false;
        })
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.bottom-menu {
  margin-top: 48px;
  text-align: center;
}
.bottom-menu-records {
  margin-top: 30px;
  text-align: center;
}
</style>
